package com.agile.leetcode.easy.reserveword;

/**
 * 给定一个字符串，你需要反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。
 * <p>
 *  
 * <p>
 * 示例：
 * <p>
 * 输入："Let's take LeetCode contest"
 * 输出："s'teL ekat edoCteeL tsetnoc"
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/reverse-words-in-a-string-iii
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * @Author:ChenZhangKun
 * @Date: 2021/2/16 21:26
 */
public class ReserveWords {
    public static void main(String[] args) {
        ReserveWords reserveWords = new ReserveWords();
        String s = reserveWords.reserveWords("Let's take LeetCode contest");
        System.out.println(s);
    }

    public String reserveWords(String s) {
        String[] strings = null;
        // 切割
        if (s != null) {
            strings = s.split(" ");
            // 遍历
            for (int i = 0; i < strings.length; i++) {
                strings[i] = reserveStr(strings[i]);
            }
        }
        // 拼接字符串
        StringBuilder builder = new StringBuilder();
        if (strings != null) {
            for (String string : strings) {
                builder.append(string).append(" ");
            }
        }
        String string = builder.toString();
        if (!"".equals(string)) {
            return string.substring(0, string.length() - 1);
        }
        return string;
    }

    /**
     * 反转字符串
     *
     * @param str
     * @return
     */
    private String reserveStr(String str) {
        // 非空判断
        if (str == "" || str.length() == 0) {
            return str;
        }
        //
        if (str.length() == 1) {
            return str;
        }
        return reserveStr(str.substring(1)) + str.substring(0, 1);
    }
}
